#ifndef AI_FARM_ANALYZER_H
#define AI_FARM_ANALYZER_H

#include <Arduino.h>

// 定义环境数据结构
typedef struct {
  float temperature;      // 温度 (°C)
  float humidity;         // 湿度 (%)
  float soilMoisture;     // 土壤湿度 (%)
  uint32_t lightIntensity; // 光照强度 (lux)
  uint16_t co2Level;      // CO2浓度 (ppm)
  unsigned long timestamp; // 时间戳
  int hourOfDay;          // 一天中的小时
} FarmEnvironmentData;

// 定义农业建议结构
typedef struct {
  bool irrigate;          // 是否需要灌溉
  bool adjustVentilation; // 是否需要调整通风
  bool adjustLighting;    // 是否需要调整光照
  float recommendedWateringTime; // 推荐灌溉时间 (分钟)
  int priorityLevel;      // 优先级 (0-5, 5为最高优先级)
} FarmRecommendation;

// 定义作物类型
enum CropType {
  TOMATO,
  CUCUMBER,
  LETTUCE,
  BASIL,
  ROSE
};

// AI农业分析器类
class AIFarmAnalyzer {
private:
  // 作物类型配置
  CropType currentCrop; 
  
  // 作物生长环境参数配置 (基于经验和研究)
  struct CropConfig {
    float idealTempMin;    // 理想温度最小值
    float idealTempMax;    // 理想温度最大值
    float idealHumidityMin; // 理想湿度最小值
    float idealHumidityMax; // 理想湿度最大值
    float idealSoilMoistureMin; // 理想土壤湿度最小值
    float idealSoilMoistureMax; // 理想土壤湿度最大值
    float criticalSoilMoisture; // 临界土壤湿度 (需要立即灌溉)
    uint32_t idealLightMin; // 理想光照最小值
    uint32_t idealLightMax; // 理想光照最大值
    uint16_t idealCo2Min;  // 理想CO2浓度最小值
    uint16_t idealCo2Max;  // 理想CO2浓度最大值
  } cropConfigs[5]; // 为每种作物存储配置
  
  // 历史数据缓冲区 (用于趋势分析)
  FarmEnvironmentData history[12]; // 存储过去60分钟的数据 (每5分钟一个样本)
  int historyIndex; // 当前历史数据索引
  
  // 学习参数 (用于自适应调整)
  float learningRate; // 学习率
  float weights[5];   // 环境参数权重
  
  // 时间和季节相关参数
  bool isDaytime;     // 是否为白天
  float seasonalFactor; // 季节性调整因子
  
  // 内部方法
  void updateHistory(const FarmEnvironmentData& data);
  float calculateEnvironmentScore(const FarmEnvironmentData& data);
  bool detectAnomalies(const FarmEnvironmentData& data);
  void adaptiveLearning(const FarmEnvironmentData& data, bool successOutcome);
  float predictFutureSoilMoisture(uint8_t minutesAhead);

public:
  // 构造函数
  AIFarmAnalyzer();
  
  // 初始化函数
  void init();
  
  // 设置作物类型
  void setCropType(CropType crop);
  
  // 分析环境数据并生成建议
  FarmRecommendation analyzeEnvironment(const FarmEnvironmentData& data);
  
  // 获取当前环境评分
  float getCurrentEnvironmentScore();
  
  // 重置学习参数
  void resetLearning();
  
  // 手动调整权重
  void setParameterWeight(uint8_t parameterIndex, float weight);
}; 

// 构造函数
AIFarmAnalyzer::AIFarmAnalyzer() {
  currentCrop = TOMATO; // 默认作物类型为番茄
  historyIndex = 0; 
  learningRate = 0.05f; // 设置学习率
  seasonalFactor = 1.0f;
  
  // 初始化权重
  weights[0] = 0.25f; // 温度权重
  weights[1] = 0.25f; // 湿度权重
  weights[2] = 0.30f; // 土壤湿度权重
  weights[3] = 0.10f; // 光照权重
  weights[4] = 0.10f; // CO2浓度权重
  
  // 初始化历史数据
  for (int i = 0; i < 12; i++) {
    history[i].temperature = 22.0f;
    history[i].humidity = 60.0f;
    history[i].soilMoisture = 60.0f;
    history[i].lightIntensity = 5000;
    history[i].co2Level = 400;
    history[i].timestamp = 0;
    history[i].hourOfDay = 12;
  }
  
  // 设置作物配置 (基于常见温室作物的理想生长条件)
  
  // 番茄配置
  cropConfigs[TOMATO] = {
    18.0f, 28.0f,   // 理想温度范围
    60.0f, 80.0f,   // 理想湿度范围
    50.0f, 80.0f,   // 理想土壤湿度范围
    40.0f,          // 临界土壤湿度
    3000, 8000,     // 理想光照范围
    400, 1000       // 理想CO2浓度范围
  };
  
  // 黄瓜配置
  cropConfigs[CUCUMBER] = {
    20.0f, 30.0f,
    70.0f, 90.0f,
    60.0f, 90.0f,
    50.0f,
    4000, 10000,
    400, 1200
  };
  
  // 生菜配置
  cropConfigs[LETTUCE] = {
    15.0f, 25.0f,
    60.0f, 70.0f,
    45.0f, 75.0f,
    35.0f,
    2000, 6000,
    400, 800
  };
  
  // 罗勒配置
  cropConfigs[BASIL] = {
    20.0f, 27.0f,
    50.0f, 70.0f,
    40.0f, 70.0f,
    30.0f,
    3000, 7000,
    400, 900
  };
  
  // 玫瑰配置
  cropConfigs[ROSE] = {
    18.0f, 25.0f,
    50.0f, 70.0f,
    40.0f, 60.0f,
    30.0f,
    3000, 6000,
    400, 800
  };
}

// 初始化函数
void AIFarmAnalyzer::init() {
  // 初始化完成
}

// 设置作物类型
void AIFarmAnalyzer::setCropType(CropType crop) {
  if (crop >= TOMATO && crop <= ROSE) {
    currentCrop = crop;
  }
}

// 分析环境数据并生成建议
FarmRecommendation AIFarmAnalyzer::analyzeEnvironment(const FarmEnvironmentData& data) {
  FarmRecommendation recommendation;
  CropConfig& config = cropConfigs[currentCrop];
  
  // 更新历史数据
  updateHistory(data);
  
  // 检测是否为白天 (根据光照强度和时间)
  isDaytime = (data.lightIntensity > 1000) || (data.hourOfDay >= 6 && data.hourOfDay <= 18);
  
  // 初始化建议
  recommendation.irrigate = false;
  recommendation.adjustVentilation = false;
  recommendation.adjustLighting = false;
  recommendation.recommendedWateringTime = 0.0f;
  recommendation.priorityLevel = 0;
  
  // 检查土壤湿度
  if (data.soilMoisture < config.criticalSoilMoisture) {
    // 紧急需要灌溉
    recommendation.irrigate = true;
    recommendation.recommendedWateringTime = 10.0f; // 10分钟
    recommendation.priorityLevel = 5;
  } else if (data.soilMoisture < config.idealSoilMoistureMin) {
    // 需要灌溉
    recommendation.irrigate = true;
    // 预测未来土壤湿度，决定灌溉时间
    float futureMoisture = predictFutureSoilMoisture(30);
    if (futureMoisture < config.criticalSoilMoisture) {
      recommendation.recommendedWateringTime = 8.0f;
      recommendation.priorityLevel = 4;
    } else {
      recommendation.recommendedWateringTime = 5.0f;
      recommendation.priorityLevel = 3;
    }
  }
  
  // 检查通风 (温度和湿度)
  if ((data.temperature > config.idealTempMax) || 
      (data.humidity > config.idealHumidityMax) ||
      (data.co2Level > config.idealCo2Max)) {
    recommendation.adjustVentilation = true;
    recommendation.priorityLevel = max(recommendation.priorityLevel, 2);
  }
  
  // 检查光照 (仅在白天考虑)
  if (isDaytime && (data.lightIntensity < config.idealLightMin || 
                   data.lightIntensity > config.idealLightMax)) {
    recommendation.adjustLighting = true;
    recommendation.priorityLevel = max(recommendation.priorityLevel, 1);
  }
  
  // 检测异常情况
  if (detectAnomalies(data)) {
    recommendation.priorityLevel = 5; // 异常情况优先级最高
  }
  
  return recommendation;
}

// 更新历史数据
void AIFarmAnalyzer::updateHistory(const FarmEnvironmentData& data) {
  history[historyIndex] = data;
  historyIndex = (historyIndex + 1) % 12;
}

// 计算环境评分
float AIFarmAnalyzer::calculateEnvironmentScore(const FarmEnvironmentData& data) {
  CropConfig& config = cropConfigs[currentCrop];
  float score = 0.0f;
  
  // 计算温度评分 (在理想范围内得满分)
  if (data.temperature >= config.idealTempMin && data.temperature <= config.idealTempMax) {
    score += weights[0] * 1.0f;
  } else {
    // 超出范围根据距离计算分数
    float tempDiff = (data.temperature < config.idealTempMin) ? 
                    (config.idealTempMin - data.temperature) : 
                    (data.temperature - config.idealTempMax);
    score += weights[0] * max(0.0f, 1.0f - tempDiff / 10.0f);
  }
  
  // 计算湿度评分
  if (data.humidity >= config.idealHumidityMin && data.humidity <= config.idealHumidityMax) {
    score += weights[1] * 1.0f;
  } else {
    float humidityDiff = (data.humidity < config.idealHumidityMin) ? 
                        (config.idealHumidityMin - data.humidity) : 
                        (data.humidity - config.idealHumidityMax);
    score += weights[1] * max(0.0f, 1.0f - humidityDiff / 20.0f);
  }
  
  // 计算土壤湿度评分
  if (data.soilMoisture >= config.idealSoilMoistureMin && 
      data.soilMoisture <= config.idealSoilMoistureMax) {
    score += weights[2] * 1.0f;
  } else {
    float soilDiff = (data.soilMoisture < config.idealSoilMoistureMin) ? 
                    (config.idealSoilMoistureMin - data.soilMoisture) : 
                    (data.soilMoisture - config.idealSoilMoistureMax);
    score += weights[2] * max(0.0f, 1.0f - soilDiff / 30.0f);
  }
  
  // 计算光照评分 (仅在白天考虑)
  if (isDaytime) {
    if (data.lightIntensity >= config.idealLightMin && 
        data.lightIntensity <= config.idealLightMax) {
      score += weights[3] * 1.0f;
    } else {
      float lightRatio;
      if (data.lightIntensity < config.idealLightMin) {
        lightRatio = (float)data.lightIntensity / (float)config.idealLightMin;
      } else {
        lightRatio = 1.0f - ((float)(data.lightIntensity - config.idealLightMax) / 10000.0f);
      }
      score += weights[3] * max(0.0f, lightRatio);
    }
  } else {
    // 晚上不考虑光照评分
    score += weights[3] * 1.0f;
  }
  
  // 计算CO2浓度评分
  if (data.co2Level >= config.idealCo2Min && data.co2Level <= config.idealCo2Max) {
    score += weights[4] * 1.0f;
  } else {
    float co2Ratio;
    if (data.co2Level < config.idealCo2Min) {
      co2Ratio = (float)data.co2Level / (float)config.idealCo2Min;
    } else {
      co2Ratio = 1.0f - ((float)(data.co2Level - config.idealCo2Max) / 1000.0f);
    }
    score += weights[4] * max(0.0f, co2Ratio);
  }
  
  return score;
}

// 检测异常情况
bool AIFarmAnalyzer::detectAnomalies(const FarmEnvironmentData& data) {
  // 计算历史平均值
  float avgTemp = 0.0f;
  float avgHumidity = 0.0f;
  float avgSoilMoisture = 0.0f;
  
  for (int i = 0; i < 12; i++) {
    avgTemp += history[i].temperature;
    avgHumidity += history[i].humidity;
    avgSoilMoisture += history[i].soilMoisture;
  }
  
  avgTemp /= 12.0f;
  avgHumidity /= 12.0f;
  avgSoilMoisture /= 12.0f;
  
  // 计算标准差 (简化版本)
  float tempVariance = 0.0f;
  float humidityVariance = 0.0f;
  
  for (int i = 0; i < 12; i++) {
    tempVariance += pow(history[i].temperature - avgTemp, 2);
    humidityVariance += pow(history[i].humidity - avgHumidity, 2);
  }
  
  float tempStd = sqrt(tempVariance / 12.0f);
  float humidityStd = sqrt(humidityVariance / 12.0f);
  
  // 检测是否有异常 (超过3倍标准差或急剧变化)
  bool tempAnomaly = fabs(data.temperature - avgTemp) > 3.0f * tempStd;
  bool humidityAnomaly = fabs(data.humidity - avgHumidity) > 3.0f * humidityStd;
  bool soilMoistureAnomaly = fabs(data.soilMoisture - avgSoilMoisture) > 20.0f;
  
  return tempAnomaly || humidityAnomaly || soilMoistureAnomaly;
}

// 获取当前环境评分
float AIFarmAnalyzer::getCurrentEnvironmentScore() {
  // 获取最新的环境数据
  int lastIndex = (historyIndex - 1 + 12) % 12;
  return calculateEnvironmentScore(history[lastIndex]);
}

// 重置学习参数
void AIFarmAnalyzer::resetLearning() {
  learningRate = 0.05f;
  weights[0] = 0.25f;
  weights[1] = 0.25f;
  weights[2] = 0.30f;
  weights[3] = 0.10f;
  weights[4] = 0.10f;
}

// 手动调整权重
void AIFarmAnalyzer::setParameterWeight(uint8_t parameterIndex, float weight) {
  if (parameterIndex < 5 && weight >= 0.0f && weight <= 1.0f) {
    weights[parameterIndex] = weight;
  }
}

// 预测未来土壤湿度
float AIFarmAnalyzer::predictFutureSoilMoisture(uint8_t minutesAhead) {
  // 简化的预测算法：基于最近几个样本的土壤湿度变化趋势
  int lastIndex = (historyIndex - 1 + 12) % 12;
  float currentMoisture = history[lastIndex].soilMoisture;
  
  // 计算平均变化率 (基于最近3个样本)
  float changeRate = 0.0f;
  int validChanges = 0;
  
  for (int i = 1; i <= 3; i++) {
    int idx1 = (lastIndex - i + 12) % 12;
    int idx2 = (lastIndex - i - 1 + 12) % 12;
    
    if (history[idx1].timestamp > 0 && history[idx2].timestamp > 0) {
      float moistureDiff = history[idx1].soilMoisture - history[idx2].soilMoisture;
      float timeDiff = (history[idx1].timestamp - history[idx2].timestamp) / 60.0f; // 转换为分钟
      
      if (timeDiff > 0) {
        changeRate += moistureDiff / timeDiff;
        validChanges++;
      }
    }
  }
  
  if (validChanges > 0) {
    changeRate /= validChanges;
  }
  
  // 预测未来土壤湿度
  float predictedMoisture = currentMoisture + (changeRate * minutesAhead);
  
  // 确保预测值在合理范围内
  if (predictedMoisture < 0.0f) predictedMoisture = 0.0f;
  if (predictedMoisture > 100.0f) predictedMoisture = 100.0f;
  
  return predictedMoisture;
}

// 自适应学习 (在实际应用中，可以根据反馈结果调整权重)
void AIFarmAnalyzer::adaptiveLearning(const FarmEnvironmentData& data, bool successOutcome) {
  // 此函数在实际应用中可以根据反馈结果调整权重
  // 在这个简化版本中暂不实现详细逻辑
}

#endif // AI_FARM_ANALYZER_H